﻿using System.Collections.Generic;
using System.Diagnostics;
using System.Xml.Linq;

namespace Bing
{
    /// <summary>
    /// Contains an array of related image, video, and text articles, as well as a property indicating the name of the collection.
    /// </summary>
    /// <remarks>This collection is not returned for all queries.</remarks>
    [DebuggerDisplay("{Name} , Count:{NewsArticles.Count}")]
    public class NewsCollection
    {

        /// <summary>
        /// Initializes a new instance of the <see cref="NewsCollection"/> class.
        /// </summary>
        public NewsCollection()
        {
            NewsArticles = new List<NewsArticle>();
        }

        /// <summary>
        /// Gets or sets the name of this collection.
        /// </summary>
        /// <value>The name of this collection.</value>
        public string Name { get; set; }

        /// <summary>
        /// Gets or sets the List of <see cref="NewsArticle"/> that constitute this <see cref="NewsCollection"/>.
        /// </summary>
        /// <value>Array of <see cref="NewsArticle"/> that constitute this <see cref="NewsCollection"/>.</value>
        /// <remarks>A collection is a grouping of related image, video and text articles.</remarks>
        public List<NewsArticle> NewsArticles { get; set; }

        /// <summary>
        /// Parses the response from the Bing API.
        /// </summary>
        /// <param name="element">The XML from the Bing API</param>
        /// <returns>A <see cref="NewsCollection" /></returns>
        public static NewsCollection ParseElement (XElement element)
        {
            NewsCollection newsCollection = new NewsCollection();

            newsCollection.Name = ApiHelper.GetElementValueOrDefault<string>(element, "Name", ApiHelper.NewsNs);
            // Get Each "NewsArticle"
            XElement newsArticles = element.Element(XName.Get("NewsArticles", ApiHelper.NewsNs));
            if (newsArticles != null)
            {
                foreach (
                    XElement newsElement in
                        newsArticles.Elements(XName.Get("NewsArticle", ApiHelper.NewsNs)))
                {
                    NewsArticle newsArticle = NewsArticle.ParseElement(newsElement);
                    newsCollection.NewsArticles.Add(newsArticle);
                }
            }

            return newsCollection;
        }

    }
}
